package com.chen.palmar.project.set;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.PayDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.AliPayEntity;
import com.chen.palmar.entity.AuthResult;
import com.chen.palmar.entity.PayResult;
import com.chen.palmar.entity.PayWXEntity;
import com.chen.palmar.entity.VipEntity;
import com.chen.palmar.wxapi.WXPayEntryActivity;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.net.entity.WXPayEntity;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * @author Chen
 * @date 2018/1/9
 * 功能描述：
 */

public class VipActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.iv_vip_head)
    CircleImageView ivVipHead;
    @Bind(R.id.tv_vip_name)
    TextView tvVipName;
    @Bind(R.id.tv_vip_desc)
    TextView tvVipDesc;
    @Bind(R.id.tv_vip_price)
    TextView tvVipPrice;
    @Bind(R.id.tv_vip_level)
    TextView tvVipLevel;
    private VipEntity.DataBean.MemberPriceBean priceBean;
    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2018011801946697";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088421561515699";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbydz8VKgcZSRniNFJzb2eqCgIjoqRgiQgJ49uOButCTGGYjAV3Jyy6YeFNTRvst70VBRiJbvmpg8YPe+ALC5BwGLdyw4a2zVodD62W0n0mgdJUPlwl9F2dJ4omRwFYQvws7XXKaVvFUdcIwL6Xx8XNYRwVApw5yxWc/K7Lc9peC4pmk1a12PxlG+6kDAVR/3OrZTE7E2dVPQUvbu9jP8TNbq03UBDchDAE3knT0HFR8eI0FvlnLc9WWWCJdxIdcwyq3/Roi8uLmjI4FURRqofAWIhX5nC5dxvwlcxJe1Q1EFnp1lB4sLKYsiDb0nfptVH0ax3n9AdaAwp8sTbYhYVAgMBAAECggEACrCaUlI4yuIB0nzn54mPlmBxhszJI1zrv60XQXfmJkR4OoFoTUe7FOfDXdedxoBeniNa1rVCJHyGkqJFWeUuM2LRJej2Cc+65XT8jKTM+VTMZTKCO0CfpeIwrBZ9frz/BcA/HQmFiY7LO75HSQjX6E7KzK5nnQGv4CrKoB9vmQwDibTtKAuJZ3OQoovG7MbIK51CgYSzdIS51GrKUV0FbtpeJDMrqR4/gUSyi42oJWcO1WnHvL527coSE2h8Xa1eV6DEtWJcoLKVTbG/1nfGv2856L6EcH2nFbW7iMnBfD91AFMhLdgwve6nsncCUNXg7pPt5p9+OcgsgwXON5OtrQKBgQDdTBJrFP9FPFU0V98zFTq2UY4k5LckAffI2+HwNlxugQXX71quOynre/wettfr/7RR3ZF3WNF69sneutSEZjTJC4VXR75qA3O/mCg5B0u8a8Go4W79gKIx9DN3fmEqCUu/ZJ/vVHhFQpn2oz9sqJz99/cfjKJ93akI0+yJCYkQLwKBgQC0N/YLi+G3C34wKiO52hkuE6t4Xtusz444TqBSUnTGUTAdJWn8aYSfkoZfCT8NL8o1tpiZ1QXGXZ21fP8KOe+4PMZjZG2ITwlVb2SCuP7JiiYzapxZJEI1wxGQXp09cbgkNXVst+I7JZAkTIkUuj5l1KwDlDXqSPIPR4v/gy5I+wKBgD9FqtZ3EG2JTItEvIpsfXb3Zn7h7gMblO8W/0ihIlhuB2+v/etm+xtbPcDCYoYVfEcT5K2M9YgE278VCAI6/sikxKEp4CWLiyKyrH1xupPK83oHyqYsizNhMP3vYnSUZ9X3PUs+iYyz+DVug4nbw9dReJTKrwLxx4zAmxarZUb9AoGAcqJSEKAmsD9QQiTb2sE/WQ7L+GImS7MunORumE641tkXyMJeu18HLFWQwWzpPWMTtbzzLo7RAI/V3Hao6AFYWZHXA6wC/DyCDGUxwvEXqG0GxZff4dftgbMWPgXg8Q+f+PBERCZncgX/vQct/xBE1pND43boIKHLzypMg/gWffcCgYAo+BNpqjDgR0GLDf+ZaX/UcA/eWP6RJkBV33083Opywjdue/X1lE2wBjZXKveClDljcSd8R9D2NsHTENzn88x66fxtjWOuEr9GmjObXWqVG56utSc9+oDEu12cF71499O8KbEjaVGidkRlQXH3hJeUJl++IBDTN/7uWQzdWG2CZA==";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked") PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //                     判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //                        Toast.makeText(VipActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        commitPayResult();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(VipActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked") AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(VipActivity.this, "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(VipActivity.this, "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private String url;
    private PayDialog payDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //微信支付测试接口，正式开发必须使用公司自己的接口
        url = "http://wxpay.wxutil.com/pub_v2/app/app_pay.php";
        //注册事件
        EventBus.getDefault().register(this);
        init();
    }

    @Override
    public void init() {
        toolBar.setNavigationOnClickListener(v -> VipActivity.this.finish());
        titleBar.setText("会员中心");

        try {
            getDataForWeb();
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
        }
    }

    private void getDataForWeb() {
        Subscription subscribe = DataCenter.vipCenter().subscribe(new HttpSubscriber<VipEntity>(this, showLoading("加载中")) {
            @Override
            public void onNext(VipEntity vipEntity) {
                VipEntity.DataBean data = vipEntity.getData();
                if (data.getMemberPrice().size() > 0) {
                    priceBean = data.getMemberPrice().get(data.getMemberPrice().size() - 1);
                    Picasso.with(VipActivity.this).load(data.getAvatar()).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).fit().into(ivVipHead);

                    tvVipName.setText(data.getUser_name());
                    tvVipLevel.setText(data.getMember_no());
                    tvVipDesc.setText("有效期：" + data.getEnd_at() + "\n" + data.getMemberPrice().get(data.getMemberPrice().size() - 1).getDesc());
                    tvVipPrice.setText("充值（" + data.getMemberPrice().get(data.getMemberPrice().size() - 1).getPrice() + "元/月）");
                }
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_set_vip;
    }

    @OnClick(R.id.ly_vip_up)
    public void onViewClicked() {
        if (priceBean == null) {
            showToast("数据加载失败，重试中");
            try {
                getDataForWeb();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
            }
            return;
        }

        payDialog = new PayDialog();
        payDialog.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ly_pay_zfb:
                        aliPay();
                        //                        showToast("现在是微信测试支付接口");
                        //                        wxPayCeshi();
                        break;
                    case R.id.ly_pay_wechat:
                        wxPay();
                        break;
                }
            }
        });
        payDialog.show(getSupportFragmentManager());
    }

    private void wxPay() {
        //        "http://wxpay.wxutil.com/pub_v2/app/app_pay.php"
        HashMap<String, String> map = new HashMap<>();
        map.put("pay_type", "1");
        Subscription subscribe = DataCenter.wxPay(map).subscribe(new HttpSubscriber<PayWXEntity>(this, showLoading("调用支付中")) {
            @Override
            public void onNext(PayWXEntity data) {
                PayWXEntity.DataBean entity = data.getData();

                IWXAPI msgApi = WXAPIFactory.createWXAPI(VipActivity.this, AppConstant.APP_WX_ID);

                // 将该app注册到微信
                msgApi.registerApp(AppConstant.APP_WX_ID);

                PayReq request = new PayReq();

                request.appId = entity.getAppid();

                request.partnerId = entity.getPartnerid();

                request.prepayId = entity.getPrepayid();

                request.packageValue = entity.getPackageX();

                request.nonceStr = entity.getNoncestr();

                request.timeStamp = entity.getTimestamp() + "";

                request.sign = entity.getSign();

                msgApi.sendReq(request);
            }
        });
        subscription.add(subscribe);
    }

    private void wxPayCeshi() {
        //        "http://wxpay.wxutil.com/pub_v2/app/app_pay.php"
        HashMap<String, String> map = new HashMap<>();
        map.put("pay_type", "1");
        Subscription subscribe = DataCenter.wxPay(url, map).subscribe(new HttpSubscriber<WXPayEntity>(this, showLoading("调用支付中")) {
            @Override
            public void onNext(WXPayEntity entity) {
                //                        PayWXEntity.DataBean entity = data.getData();

                IWXAPI msgApi = WXAPIFactory.createWXAPI(VipActivity.this, AppConstant.APP_WX_ID);

                // 将该app注册到微信
                msgApi.registerApp(AppConstant.APP_WX_ID);

                PayReq request = new PayReq();

                request.appId = entity.getAppid();

                request.partnerId = entity.getPartnerid();

                request.prepayId = entity.getPrepayid();

                request.packageValue = entity.getPackageX();

                request.nonceStr = entity.getNoncestr();

                request.timeStamp = entity.getTimestamp() + "";

                request.sign = entity.getSign();

                msgApi.sendReq(request);
            }
        });
        subscription.add(subscribe);
    }


    private void aliPay() {
        HashMap<String, String> map = new HashMap<>();
        map.put("pay_type", "2");
        Subscription subscribe = DataCenter.aliPay(map).subscribe(new HttpSubscriber<AliPayEntity>(this, showLoading("调用支付中")) {
            @Override
            public void onNext(AliPayEntity data) {
                startAliPay(data.getData());
            }
        });
        subscription.add(subscribe);
    }

    private void startAliPay(String data) {
        /**
         * 支付宝支付业务
         *
         */
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    finish();
                }
            }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        //        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        //        Map<String, String> params = OrderInfoUtil.buildOrderParamMap(APPID, rsa2);
        //        String orderParam = OrderInfoUtil.buildOrderParam(params);
        //
        //        String privateKey = RSA2_PRIVATE;
        //        String sign = OrderInfoUtil.getSign(params, privateKey, rsa2);
        ////        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(VipActivity.this);
                Map<String, String> result = alipay.payV2(data, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventType()) {
            case WXPayEntryActivity.EVENT_WX_PAY_CODE:
                commitPayResult();
                break;
        }
    }

    private void commitPayResult() {
        if (payDialog != null) {
            payDialog.dismiss();
        }
        showToast("支付成功");
        //        HashMap<String, String> map = new HashMap<>();
        //        map.put("price_id", priceBean.getPrice_id() + "");
        //        Subscription subscribe = DataCenter.openVip(map).subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading("加载中")) {
        //            @Override
        //            public void onNext(HttpResultEntity entity) {
        //                showToast(entity.getMessage());
        getDataForWeb();
        //            }
        //        });
        //        subscription.add(subscribe);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }
}
